from flask_restful import Resource
from flask import request
from apps.api.v1 import api, get_result
from apps.models import User


class UserResource(Resource):
    def get(self, id):
        """查询单个用户"""
        result = get_result()
        user = User.select().where(User.id == id).get()
        result['data'] = [user.dict]
        return result

    def put(self, id):
        """修改单个用户"""
        result = get_result()
        args = request.json
        user = User.select().where(User.id == id).get()
        user.username = args.get('username')
        user.password = args.get('password')
        from datetime import datetime
        user.update_time = datetime.now()
        user.save()
        return result

    def delete(self, id):
        """删除单个用户"""
        result = get_result()
        User.delete().where(User.id == id).execute()
        return result


class UserListResource(Resource):
    def get(self):
        """查询所有用户"""
        result = get_result()
        data = list(User.select().dicts())
        result['data'] = data
        return result

    def post(self):
        """添加用户"""
        result = get_result()
        args = request.json
        user = User(
            username=args.get('username'),
            password=args.get('password')
        )
        user.save()
        return result


api.add_resource(UserListResource, '/users', endpoint="users")
api.add_resource(UserResource, '/user/<int:id>', endpoint="user")
